package cn.xchats.onlinetraffic.data.server.rest;

import cn.xchats.onlinetraffic.common.dto.ComparisonInfoDto;
import cn.xchats.onlinetraffic.common.dto.ShopDto;
import cn.xchats.onlinetraffic.common.other.mq.AMQPServer;
import cn.xchats.onlinetraffic.common.type.AMQPType;
import cn.xchats.onlinetraffic.common.type.CollectType;
import cn.xchats.onlinetraffic.common.type.CollectWebsiteType;
import cn.xchats.onlinetraffic.data.server.server.CollectorService;
import cn.xchats.onlinetraffic.jooq.frame.common.BaseBean;
import cn.xchats.onlinetraffic.jooq.frame.common.MessageBean;
import org.jooq.tools.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

/*
 *
 *@author teddy
 *@date 2018/4/16
 */
@RestController
@RequestMapping("/collector")
public class CollectorController {

    @Autowired
    private CollectorService collectorService;

    @Autowired
    private AMQPServer amqpServer;

    //测试完毕
    @RequestMapping(value = "/fieldList", method = RequestMethod.GET)
    public BaseBean list() {
        return collectorService.getFieldList();
    }

    @RequestMapping(value = "/collectWebsiteList", method = RequestMethod.GET)
    public BaseBean getCollectWebsiteList() {
        return collectorService.getCollectWebsiteList();
    }

    //测试完毕
    @RequestMapping(value = "/saveCollectCategory", method = RequestMethod.POST)
    public BaseBean save(String category, String fieldName, String executeJavascript) {
        return collectorService.saveCollectCategory(category, fieldName, executeJavascript);
    }

    //测试完毕
    @RequestMapping(value = "/saveField", method = RequestMethod.POST)
    public BaseBean saveField(String field, String order) {
        return collectorService.saveField(field, order);
    }

    //测试完毕
    @RequestMapping(value = "/collectRuleList", method = RequestMethod.GET)
    public BaseBean getCollectRuleList(HttpServletRequest request) {
        return collectorService.getCollectRuleList();
    }

    //测试完毕
    @RequestMapping(value = "/saveCollectList_1688", method = RequestMethod.POST)
    //@Async("executor_fixed_4")
    public BaseBean saveCollectList(String userId, String url) {
        MessageBean<Object> messageBean = new MessageBean<>();
        if (StringUtils.isBlank(url)) {
            messageBean.setMeta("请输入网址!");
            return messageBean;
        }
        //check redis  同一段时间内不能多次提交
        MessageBean checkResult = collectorService.checkCollectTaskRecord(CollectType.LIST_HOME_1688, url, null, userId).valueOf(MessageBean.class);
        if (checkResult.getData()!=null){
            messageBean.setMeta("任务已存在,请勿重复提交-redis");
            return messageBean;
        }

        messageBean = collectorService.existShop(CollectType.LIST_HOME_1688, url, null, userId).valueOf(MessageBean.class);
        if (messageBean.getData() != null) {
            messageBean.setMeta("任务已存在,请勿重复提交");
            return messageBean;
        }

        /*ExecutorServiceUtil.getmethods.getExecutor().execute(() -> {
            collectorService.saveCollectList(userId, CollectType.LIST_HOME_1688, url);
        });*/
        amqpServer.send(AMQPType.LIST_HOME,"userId",userId,"shopCategory", CollectType.LIST_HOME_1688,"collectWebsiteType", CollectWebsiteType.category_1688,"url",url);

        messageBean.setData(null);
        messageBean.setMeta("已提交，正在执行,请稍后");
        return messageBean;
    }

    @RequestMapping(value = "/saveCollectList_taobao", method = RequestMethod.POST)
    //@Async("executor_fixed_4")
    public BaseBean saveCollectList_taobao(String userId, String url) {
        MessageBean<Object> messageBean = new MessageBean<>();
        if (StringUtils.isBlank(url)) {
            messageBean.setMeta("请输入网址!");
            return messageBean;
        }
        //check redis  同一段时间内不能多次提交
        MessageBean checkResult = collectorService.checkCollectTaskRecord(CollectType.LIST_HOME_TAO_BAO, url, null, userId).valueOf(MessageBean.class);
        if (checkResult.getData()!=null){
            messageBean.setMeta("任务已存在,请勿重复提交-redis");
            return messageBean;
        }

        messageBean = collectorService.existShop(CollectType.LIST_HOME_TAO_BAO, url, null, userId).valueOf(MessageBean.class);
        if (messageBean.getData() != null) {
            messageBean.setMeta("任务已存在,请勿重复提交");
            return messageBean;
        }

        /*ExecutorServiceUtil.getmethods.getExecutor().execute(() -> {
            collectorService.saveCollectList(userId, CollectType.LIST_HOME_1688, url);
        });*/
        amqpServer.send(AMQPType.LIST_HOME,"userId",userId,"shopCategory", CollectType.LIST_HOME_TAO_BAO,"collectWebsiteType", CollectWebsiteType.category_tao_bao,"url",url);

        messageBean.setData(null);
        messageBean.setMeta("已提交，正在执行,请稍后");
        return messageBean;
    }

    //测试完毕
    @RequestMapping(value = "/collectList_1688", method = RequestMethod.GET)
    public BaseBean collectList_1688(String userId , int currentPage, int limit) {
        return collectorService.getCollectList(userId, CollectType.LIST_HOME_1688,currentPage,limit);
    }

    @RequestMapping(value = "/collectList_tao_bao", method = RequestMethod.GET)
    public BaseBean collectList_tao_bao(String userId, int currentPage, int limit) {
        return collectorService.getCollectList(userId, CollectType.LIST_HOME_TAO_BAO,currentPage,limit);
    }

    //count
    //测试完毕
    @RequestMapping(value = "/collectList_1688_count", method = RequestMethod.GET)
    public BaseBean collectList_1688_count(String userId ) {
        return collectorService.getCollectListCount(userId, CollectType.LIST_HOME_1688);
    }

    @RequestMapping(value = "/collectList_tao_bao_count", method = RequestMethod.GET)
    public BaseBean collectList_tao_bao_count(String userId) {
        return collectorService.getCollectListCount(userId, CollectType.LIST_HOME_TAO_BAO);
    }

    //测试完毕
    @RequestMapping(value = "/saveSearchImageShopUrl_tao_bao", method = RequestMethod.POST)
    // @Async("executor_fixed_4")
    public BaseBean saveSearchImageShopUrl_tao_bao(String userId, String shopId, String shopUrl, String imgUrl) {
        MessageBean<Object> messageBean = new MessageBean<>();
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(shopId) || StringUtils.isBlank(shopUrl) || StringUtils.isBlank(imgUrl)) {
            messageBean.setMeta("该商品信息有误，无法对比");
            return messageBean;
        }
        //check redis  同一段时间内不能多次提交
        MessageBean checkResult = collectorService.checkCollectTaskRecord(CollectType.LIST_DETAILS_TAO_BAO, null, shopId, userId).valueOf(MessageBean.class);
        if (checkResult.getData()!=null){
            messageBean.setMeta("任务已存在,请勿重复提交");
            return messageBean;
        }

        messageBean = collectorService.existShop(CollectType.LIST_DETAILS_TAO_BAO, null, shopId, userId).valueOf(MessageBean.class);
        if (messageBean.getData() != null) {
            messageBean.setMeta("任务已存在,请勿重复提交");
            return messageBean;
        }

        shopUrl = "https://www.taobao.com/";
        final String url = shopUrl;
      /*  ExecutorServiceUtil.getmethods.getExecutor().execute(() -> {
            collectorService.saveSearchImageShopUrl_tao_bao(userId, shopId, CollectType.LIST_DETAILS_TAO_BAO, url, imgUrl);
        });*/
        amqpServer.send(AMQPType.LIST_DETAILS_TAO_BAO,"userId",userId,"category", CollectType.LIST_DETAILS_TAO_BAO,"shopId", shopId,"shopUrl",url,"imgUrl",imgUrl);

        messageBean.setData(null);
        messageBean.setMeta("已提交，正在执行,请稍后");
        return messageBean;
    }

    //测试完毕
    @RequestMapping(value = "/saveSearchImageShopUrl_1688", method = RequestMethod.POST)
    //@Async("executor_fixed_4")
    public BaseBean saveSearchImageShopUrl_1688(String userId, String shopId, String shopUrl, String imgUrl) {
        MessageBean<Object> messageBean = new MessageBean<>();
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(shopId) || StringUtils.isBlank(shopUrl) || StringUtils.isBlank(imgUrl)) {
            messageBean.setMeta("该商品信息有误，无法对比");
            return messageBean;
        }
        //check redis  同一段时间内不能多次提交
        MessageBean checkResult = collectorService.checkCollectTaskRecord(CollectType.LIST_DETAILS_1688, null, shopId, userId).valueOf(MessageBean.class);
        if (checkResult.getData()!=null){
            messageBean.setMeta("任务已存在,请勿重复提交");
            return messageBean;
        }

        messageBean = collectorService.existShop(CollectType.LIST_DETAILS_1688, null, shopId, userId).valueOf(MessageBean.class);
        if (messageBean.getData() != null) {
            messageBean.setMeta("任务已存在,请勿重复提交");
            return messageBean;
        }

        shopUrl = "https://www.1688.com/";
        final String url = shopUrl;
        /*ExecutorServiceUtil.getmethods.getExecutor().execute(() -> {
            collectorService.saveSearchImageShopUrl_1688(userId, shopId, CollectType.LIST_DETAILS_1688, url, imgUrl);
        });*/

        amqpServer.send(AMQPType.LIST_DETAILS_1688,"userId",userId,"category", CollectType.LIST_DETAILS_1688,"shopId", shopId,"shopUrl",url,"imgUrl",imgUrl);

        messageBean.setData(null);
        messageBean.setMeta("已提交，正在执行,请稍后");
        return messageBean;
    }

    //测试完毕
    @RequestMapping(value = "/itemList", method = RequestMethod.GET)
    public BaseBean getItemList(String category, String shopId) {
        if (!CollectType.LIST_DETAILS_TAO_BAO.name().equals(category) && !CollectType.LIST_DETAILS_1688.name().equals(category))
            return new MessageBean<>().setFieldValue("meta", "分类传参错误.");
        MessageBean result = collectorService.getItemList(shopId, category).valueOf(MessageBean.class);
        if (result.getData() == null)
            return result;

        List<ComparisonInfoDto> comparisonInfoDtoList;
        ShopDto data = (ShopDto) result.getData();
        comparisonInfoDtoList = data.getComparisonInfoDtoList();
        long s = System.currentTimeMillis();
        //排序价格
        Collections.sort(comparisonInfoDtoList, (a, b) -> {
            String price_1 = a.getPrice();
            String price_2 = b.getPrice();
            double dealCat_1_double = Double.valueOf(price_1.substring(1));
            double dealCat_2_double = Double.valueOf(price_2.substring(1));
            double compare = dealCat_2_double - dealCat_1_double;
            return (int) compare;
        });
        //排序销量
        if (CollectType.LIST_DETAILS_1688.name().equals(category)) {
            Collections.sort(comparisonInfoDtoList, (a, b) -> {
                try {
                    String dealCnt_1 = a.getDealCnt();
                    String dealCnt_2 = b.getDealCnt();
                    int dealCat_1_int = 0;
                    try {
                        dealCat_1_int = Integer.valueOf(dealCnt_1.substring(3, dealCnt_1.length() - 1));
                    } catch (NumberFormatException e) {
                        dealCat_1_int = Integer.valueOf(dealCnt_1.substring(3, dealCnt_1.length() - 2).replace(".", "") + "00");
                    }
                    int dealCat_2_int = 0;
                    try {
                        dealCat_2_int = Integer.valueOf(dealCnt_2.substring(3, dealCnt_2.length() - 1));
                    } catch (NumberFormatException e) {
                        dealCat_2_int = Integer.valueOf(dealCnt_2.substring(3, dealCnt_2.length() - 2).replace(".", "") + "00");
                    }
                    return dealCat_2_int - dealCat_1_int;
                } catch (Exception e) {
                    e.printStackTrace();
                    return -1;
                }
            });
        }
        if (CollectType.LIST_DETAILS_TAO_BAO.name().equals(category)) {
            Collections.sort(comparisonInfoDtoList, (a, b) -> {
                String dealCnt_1 = a.getDealCnt();
                String dealCnt_2 = b.getDealCnt();
                int dealCat_1_int = Integer.valueOf(dealCnt_1.substring(0, dealCnt_1.indexOf("人")));
                int dealCat_2_int = Integer.valueOf(dealCnt_2.substring(0, dealCnt_2.indexOf("人")));
                return dealCat_2_int - dealCat_1_int;
            });
        }
        System.out.println(System.currentTimeMillis() - s);
        return result;
    }

    //测试完毕
    //基本测试完毕，还需要添加删除详情的逻辑
    @RequestMapping(value = "/deleteShop",method = RequestMethod.POST)
    public BaseBean deleteShop(String shopId) {
        MessageBean<Object> result = new MessageBean<>();
        if (StringUtils.isBlank(shopId)){
            result.setMeta("参数有误,删除失败..!");
            return result;
        }
        collectorService.deleteShop(shopId);
        result.setMeta("删除成功");
        return result;
    }

}
